package org.zcl.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.zcl.utils.QueryService;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;

/**
 * @Package org.zcl.customer
 * @PROJECT_NAME: question
 * @DESCRIPTION:
 * @USER: zhuchenglin
 * @DATE: 2021/12/3 13:38
 */
@Slf4j
@Service
public class QueryAsyncServiceImpl implements QueryService {

    private static final ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 20, 200L,
            TimeUnit.MICROSECONDS, new LinkedBlockingQueue<>(400),
            new ThreadFactory() {
                final ThreadFactory defaultFactory = Executors.defaultThreadFactory();

                @Override
                public Thread newThread(Runnable r) {
                    Thread thread = defaultFactory.newThread(r);
                    thread.setName("QueryAsyncServiceImpl-" + thread.getName());
                    return thread;
                }
            }, new ThreadPoolExecutor.AbortPolicy());

    public List<String> query() throws Exception {
        List<String> list = new ArrayList<>();
        long start = System.currentTimeMillis();
        try {
            TimeUnit.MILLISECONDS.sleep(1000);
            list.add("频道");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("module接口耗时统计：频道模块耗时:{}", System.currentTimeMillis() - start);

        CompletableFuture<List<String>> future1 = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.MILLISECONDS.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return Arrays.asList("轮播图");
        }, executor);
        CompletableFuture<List<String>> future2 = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.MILLISECONDS.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return Arrays.asList("金刚区");
        }, executor);
        CompletableFuture.allOf(future1, future2).get();
        List<String> vos1 = future1.get();
        List<String> vos2 = future2.get();
        System.out.println(vos1);
        System.out.println(vos2);

        log.info("module接口耗时统计：{}", System.currentTimeMillis() - start);
        return list;
    }


}
